package com.demo.validation;

import com.demo.validation.param_validation.ParamValidationDemo;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * @author ayatsuji
 * @date 2021-06-14 00:30
 * @since
 */
@RestControllerAdvice(assignableTypes = {ParamValidationDemo.class})
public class ExceptionControl {
    @ExceptionHandler(Exception.class)
    public String handle(Exception e) {
        return e.getClass().getName();
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public String handle(MethodArgumentTypeMismatchException e) {
        return "参数" + e.getName() + "类型错误";
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public String handle2(ConstraintViolationException e) {
        StringBuilder builder = new StringBuilder();
        for (ConstraintViolation<?> v: e.getConstraintViolations()) {
            String paramName = ((PathImpl) v.getPropertyPath()).getLeafNode().asString();
            builder.append(paramName)
                    .append(v.getMessage())
                    .append(", 当前传值为[")
                    .append(v.getInvalidValue())
                    .append("]; ");
        }
        return builder.toString();
    }

    @ExceptionHandler(BindException.class)
    public String handle(BindException e) {
        final String objectName = e.getAllErrors().get(0).getObjectName();
        final String defaultMessage = e.getAllErrors().get(0).getDefaultMessage();
        return objectName + defaultMessage;
    }

}
